package cn.xo68.ide.plugin.common;

import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.ModalityHelper;
import com.intellij.ui.mac.foundation.MacUtil;

import javax.swing.*;
import java.awt.*;

public final class GuiUtils {

    public static void  openDialog(JDialog dialog, String title,int width, int height){
        openDialog(dialog, title, width, height, true);
    }
    public static void  openDialog(JDialog dialog, String title,int width, int height, boolean modal){
        dialog.setModal(modal);
        dialog.pack();
        dialog.setTitle(title);
        dialog.setSize(width, height);
        dialog.setResizable(false);
        //dialog.setLocationRelativeTo(dialog.getOwner());
        dialog.setVisible(true);
    }

    public static Window getIdeaWindow(){
        Window _window = null;
        IdeFocusManager ideFocusManager = IdeFocusManager.getGlobalInstance();

        Component focusOwner = IdeFocusManager.findInstance().getFocusOwner();
        // Let's ask for a focused component first
        if (focusOwner != null) {
            _window = SwingUtilities.getWindowAncestor(focusOwner);
        }

        if (_window == null) {
            // Looks like ide lost focus, let's ask about the last focused component
            focusOwner = ideFocusManager.getLastFocusedFor(ideFocusManager.getLastFocusedFrame());
            if (focusOwner != null) {
                _window = SwingUtilities.getWindowAncestor(focusOwner);
            }
        }

        if (_window == null) {
            _window = WindowManager.getInstance().findVisibleFrame();
        }


        if (_window != null) {
            // We have successfully found the window
            // Let's check that we have not missed a blocker
            if (ModalityHelper.isModalBlocked(_window)) {
                _window = ModalityHelper.getModalBlockerFor(_window);
            }
        }

        while (_window != null && MacUtil.getWindowTitle(_window) == null) {
            _window = _window.getOwner();
            //At least our frame should have a title
        }

        while (Registry.is("skip.untitled.windows.for.mac.messages") && _window instanceof JDialog && !((JDialog)_window).isModal()) {
            _window = _window.getOwner();
        }

        return _window;
    }
}
